package com.yunwrite.playerlibrary.customplayer.playmanager;

import android.content.Context;
import android.graphics.SurfaceTexture;
import android.media.MediaPlayer;
import android.media.TimedText;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.Surface;
import android.widget.SeekBar;

import com.yunwrite.playerlibrary.customplayer.player.CustomPlayer;
import com.yunwrite.playerlibrary.customplayer.player.CustomPlayerManager;
import com.yunwrite.playerlibrary.customplayer.videolist.VideoInfo;
import com.yunwrite.playerlibrary.customplayer.videolist.VideoListManager;
import com.yunwrite.playerlibrary.customplayer.videolist.VideoListObserver;

import java.io.IOException;
import java.util.ArrayList;

/**
 * @author liuping
 */
public class PlayManager implements VideoListObserver {

    private CustomPlayer customPlayer = CustomPlayer.getInitCustomPlayer( );
    private CustomPlayer nextPlayer = CustomPlayer.getInitCustomPlayer( );
    /**
     * 界面，接受player的输出数据，并显示到屏幕
     */
    private Surface surface;
    private SeekBar seekBar;
    private VideoListManager videoListManager;
    private VideoPlayObserver videoPlayObserver;

    public SeekBar getSeekBar() {
        return seekBar;
    }

    public void setSeekBar(SeekBar seekBar) {
        this.seekBar = seekBar;
    }

    public VideoPlayObserver getVideoPlayObserver() {
        return videoPlayObserver;
    }

    public void setVideoPlayObserver(VideoPlayObserver videoPlayObserver) {
        this.videoPlayObserver = videoPlayObserver;
    }

    private PlayManager() {
    }

    /**
     * 获取播放控制器的实例
     *
     * @return
     */
    public static PlayManager getInstance() {
        return new PlayManager( );
    }

    /**
     * 获取SurfaceTexture
     *
     * @return
     */
    public Surface getSurface() {
        return surface;
    }

    /**
     * 设置SurfaceTexture
     *
     * @param surface
     */
    public void setSurface(Surface surface) {
        this.surface = surface;
    }

    /**
     * 获取播放列表管理器
     *
     * @return
     */
    public VideoListManager getVideoListManager() {
        /**
         * 监听播放列表变化
         */
        videoListManager.setObserver(this);
        return videoListManager;
    }

    /**
     * 设置播放列表管理器
     *
     * @param videoListManager
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public void setVideoListManager(VideoListManager videoListManager) {
        this.videoListManager = videoListManager;
        update(videoListManager.getVideoInfos( ));
    }

    /**
     * 播放列表更新了
     *
     * @param videoInfoArrayList
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void update(ArrayList<VideoInfo> videoInfoArrayList) {
        //如果当前播放器处于空闲状态，则开始播放
        if (videoInfoArrayList.size( ) > 0 && CustomPlayer.FREE == customPlayer.getState( )) {
            prepare(customPlayer);
        }
    }

    /**
     * 预加载视频
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public void prepare(final CustomPlayer player) {
        try {
            VideoInfo prepare = videoListManager.prepare( );
            if (null == prepare) {
                return;
            }
            String url = prepare.getUrl( );
            if (TextUtils.isEmpty(url)) {
                return;
            }
            player.setDataSource(url);
            player.prepareAsync( );
            player.setOnPreparedListener(new MediaPlayer.OnPreparedListener( ) {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    player.setState(CustomPlayer.PREPARED);
                    if (player == customPlayer) {
                        //如果是当前视频的话，播放，如果不是，则不播放
                        try {
                            start(player);
                        } catch (IOException e) {
                            e.printStackTrace( );
                        }
                    }
                }
            });
            player.setOnCompletionListener(new MediaPlayer.OnCompletionListener( ) {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    customPlayer.stop( );
                    customPlayer.reset( );
                    customPlayer = nextPlayer;
                    nextPlayer = CustomPlayerManager.getCustomPlayer( );
                    try {
                        start(customPlayer);
                    } catch (IOException e) {
                        e.printStackTrace( );
                    }
                }
            });
            player.setState(CustomPlayer.PREPARE);
        } catch (IOException e) {
            e.printStackTrace( );
        }
    }

    /**
     * 播放并设置下一曲
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public void start(final CustomPlayer player) throws IOException {
        if (CustomPlayer.PREPARED == customPlayer.getState( )) {
            player.start( );
        } else if(CustomPlayer.PREPARE == customPlayer.getState( )) {
            player.setOnPreparedListener(new MediaPlayer.OnPreparedListener( ) {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    if (player == customPlayer) {
                        //如果是当前视频的话，播放，如果不是，则不播放
                        player.setState(CustomPlayer.PREPARED);
                        try {
                            start(player);
                        } catch (IOException e) {
                            e.printStackTrace( );
                        }
                    }
                }
            });

            return;
        }else{
            return;
        }


        player.setState(CustomPlayer.PLAYING);
        prepare(nextPlayer);
        if (null != surface) {
            player.setSurface(surface);
        }
        if (null != seekBar) {
            //应该开启线程，定时刷新进度条

            seekBar.setMax(player.getDuration( ));
            seekBar.setProgress(player.getCurrentPosition( ));

//            player.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener( ) {
//                @Override
//                public void onBufferingUpdate(MediaPlayer mp, int percent) {
//                    seekBar.setMax(player.getDuration());
//                    seekBar.setProgress(player.getCurrentPosition());
//                }
//            });
//            new SeekBarUtils(player,seekBar).StartProgress();
            new SeekBarThread( ).start( );
            //设置滑动监听
            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener( ) {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    if (fromUser) {
                        customPlayer.seekTo(progress);
                    }
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {

                }
            });
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void setNextMediaPlayer(CustomPlayer player, CustomPlayer nextMediaPlayer) {
        prepare(nextMediaPlayer);

    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public void next() {
        customPlayer.seekTo(customPlayer.getDuration( ));
        customPlayer.start( );
    }

    Handler handler = new Handler( ) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (null != customPlayer && customPlayer.getState( ) == CustomPlayer.PLAYING) {
                seekBar.setMax(customPlayer.getDuration( ));
                seekBar.setProgress(customPlayer.getCurrentPosition( ));
            }
        }
    };

    public class SeekBarThread extends Thread {
        public SeekBarThread() {
        }
        @Override
        public void run() {
            super.run( );
            while (true) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace( );
                }
                handler.sendEmptyMessage(0);
            }
        }
    }
}
